﻿using System;
using System.Collections.Generic;
using System.Text;
using System.IO;
using Tamir.SharpSsh.jsch;

namespace Tamir.SharpSsh
{

    /// <summary>
    /// SFP_基本信息
    /// </summary>
    public class SFP_RealTimeInfo
    {
        /// <summary>
        /// 温度
        /// </summary>
        public string Temperature_ALL
        {
            set;
            get;
        }
        /// <summary>
        /// 电压
        /// </summary>
        public string Voltage_ALL
        {
            set;
            get;
        }
        /// <summary>
        /// 发射功率
        /// </summary>
        public string Bias_ALL
        {
            set;
            get;
        }
        /// <summary>
        /// 发射功率
        /// </summary>
        public string TX_Laser_Power_ALL
        {
            set;
            get;
        }
        /// <summary>
        /// 接收功率
        /// </summary>
        public string RX_Laser_Power_ALL
        {
            set;
            get;
        }

        /// <summary>
        /// 温度
        /// </summary>
        public string Temperature
        {
            set;
            get;
        }
        public string Voltage
        {
            set;
            get;
        }
        public string Bias
        {
            set;
            get;
        }
        public string TX_Laser_Power
        {
            set;
            get;
        }

        public string RX_Laser_Power
        {
            set;
            get;
        }
    }
    /// <summary>
    /// SFP_基本信息
    /// </summary>
    public class SFP_BaseInfo
    {
        public string Nominal_Bit_Rate
        {
            set;
            get;
        }
        public string Link_length_supported
        {
            set;
            get;
        }
        public string Vendor_Name
        {
            set;
            get;
        }
        public string Vendor_part_number
        {
            set;
            get;
        }
        public string Wave_length
        {
            set;
            get;

        }
        public string Vendor_serial_number
        {
            set;
            get;
        }
    }

    /// <summary>
    /// SHELL 的连接类
    /// 使用例子
    /// 
    /// 
    /// </summary>
    public class ShellHelp
    {
        /*
                String host ="10.69.66.67";
                String user = "toor4nsn";
                String pwd = "oZPS0POrRieRtu";
                int Port = 22;

                Tamir.SharpSsh.ShellHelp shell = new Tamir.SharpSsh.ShellHelp();

                //连接linux成功 

                if (shell.OpenShell(host, user, pwd, Port))
                {
         *      // shell.IsConnected
                
                //cat /sys/class/sfp/sfp_0_0/rx_los
                //ssh toor4nsn@192.168.253.18

                shell.Shell("ssh toor4nsn@192.168.253.18");//执行获取命令   
                //shell.Shell("df -h");/
                // shell.Shell("dmidecode");//执行获取命令 
         * 
         *      Shell.SessionLog.返回结果
         *      
                string info = shell.GetAllString();//获取返回结果 
                shell.Shell("oZPS0POrRieRtu");//执行获取命令  
 
                info = shell.GetAllString();//获取返回结果 

                shell.Shell("cat /sys/class/sfp/sfp_0_0/diagnostics_and_control/RX_Power");//执行获取命令  

                info = shell.GetAllString();//获取返回结果 

                //Console.WriteLine(info);
                Console.WriteLine(shell.SessionLog);

                shell.Shell("cat /sys/class/sfp/sfp_0_0/rx_los");//执行获取命令  
                Console.WriteLine(shell.SessionLog);

         */

        public int TimeOutSecond = 30; //超时时间 30秒
        public string SessionLog = string.Empty;
        public bool IsConnected = false;


        System.IO.MemoryStream outputstream = new MemoryStream();
        Tamir.SharpSsh.SshStream inputstream = null;

        Channel channel = null;
        Session session = null;

        private string host
        {
            get;
            set;
        }
        private string username
        {
            get;
            set;
        }
        private string pwd
        {
            get;
            set;
        }
        private int Port
        {
            get;
            set;
        }

        public ShellHelp()
        { }

        public ShellHelp(string host, string username, string pwd)
        {
            this.host = host;
            this.username = username;
            this.pwd = pwd;
        }
        public ShellHelp(string host, string username, string pwd, int port)
        {
            this.host = host;
            this.username = username;
            this.pwd = pwd;
            this.Port = port;
        }
        /// <summary> 
        /// 命令等待标识 
        /// </summary> 
        string waitMark = ">";
        /// <summary> 
        /// 打开连接 
        /// </summary> 
        /// <param name="host"></param> 
        /// <param name="username"></param> 
        /// <param name="pwd"></param> 
        /// <returns></returns> 
        public bool OpenShell(string host, string username, string pwd)
        {
            try
            {
                inputstream = new Tamir.SharpSsh.SshStream(host, username, pwd);
                ///我手动加进去的方法。。为了读取输出信息 
                inputstream.set_OutputStream(outputstream);
                IsConnected = inputstream != null;
                return IsConnected;
            }
            catch { throw; }
        }
        /// <summary> 
        /// 打开连接 
        /// </summary> 
        /// <param name="host"></param> 
        /// <param name="username"></param> 
        /// <param name="pwd"></param> 
        /// <returns></returns> 
        public bool OpenShell(string host, string username, string pwd, int Port)
        {
            try
            {
                //Redirect standard I/O to the SSH channel 
                inputstream = new Tamir.SharpSsh.SshStream(host, username, pwd, Port);
                //我手动加进去的方法。。为了读取输出信息 
                inputstream.set_OutputStream(outputstream);
                //inputstream.set_ExOutputStream(outputstream);

                IsConnected = (inputstream != null);
                return IsConnected;
            }
            catch { throw; }
        }
        /// <summary> 

        /// 执行命令 
        /// </summary> 
        /// <param name="cmd"></param> 
        public bool Shell(string cmd)
        {
            if (inputstream == null)
                return false;

            string initinfo = GetAllString();

            inputstream.Write(cmd);

            inputstream.Flush();/*输入框情况*/
            outputstream.Flush();

            /*如何情况 历史？*/
            string currentinfo = GetAllString();


            for (int i = TimeOutSecond; i > 0; i--)
            {
                if (currentinfo == initinfo) //等待时间
                {
                    
                    {
                        System.Threading.Thread.Sleep(1000);/*需要调试*/
                    }
                    currentinfo = GetAllString();
                    continue;
                }
                else
                {
                    /*
                     ssh: connect to host 192.168.1.33 port 22: Connection refused
                     */
                    if (initinfo + cmd+"\r\n" == currentinfo)
                    {
                        System.Threading.Thread.Sleep(1000);/*需要调试*/
                        currentinfo = GetAllString();
                        continue;
                    }
                    else
                    {
                        GetSession(initinfo, currentinfo);/*fengxichu jieguo */
                        return true;
                    }
                }
            }

            return false;//命令执行超时了 就退出返回False 

        }
        public bool Conect()
        {
            if (this.Port == null)
            {
                this.Port = 22;
            }

            inputstream = new Tamir.SharpSsh.SshStream(host, username, pwd, Port);
            inputstream.set_OutputStream(outputstream);
            //inputstream.set_ExOutputStream(outputstream);
            IsConnected = (inputstream != null);
            return IsConnected;
        }


        /// <summary> 
        /// 获取输出信息  30秒超时
        /// </summary> 
        /// <returns></returns> 
        public string GetAllString()
        {
            string outinfo = Encoding.UTF8.GetString(outputstream.ToArray());
            //等待命令结束字符 
            //while (!outinfo.Trim().EndsWith(waitMark)) //]$ 可能是这个
            //{
            //for (int i = TimeOutSecond; i > 0; i--)
            //{
            //    if (!outinfo.Trim().EndsWith(waitMark)) //命令结束符 以 >结束
            //    {
            //        System.Threading.Thread.Sleep(1000);
            //        outinfo = Encoding.UTF8.GetString(outputstream.ToArray());
            //    }
            //    else
            //    {
            //        break;
            //    }
            //}
            //}
            //outinfo = Encoding.UTF8.GetString(outputstream.ToArray());

            outputstream.Flush();
            return outinfo.ToString();

        }

        /// <summary>
        /// 获取命令结果的返回
        /// </summary>
        /// <returns></returns>
        public string GetCmdString()
        {
            /*
             * 刷新 outputstream
             一直到 outputstream 有结尾符
             */
            string outinfo = Encoding.UTF8.GetString(outputstream.ToArray());
            //等待命令结束字符 
            //while (!outinfo.Trim().EndsWith(waitMark)) //]$ 可能是这个
            //{
            //}
            for (int i = TimeOutSecond; i > 0; i--)
            {
                if (!outinfo.Trim().EndsWith(waitMark)) //命令结束符 以 >结束
                {
                    System.Threading.Thread.Sleep(1000);
                    outinfo = Encoding.UTF8.GetString(outputstream.ToArray());
                }
                else
                {
                    break;
                }
            }
            outputstream.Flush();
            return outinfo.ToString();

        }
        /// <summary> 
        /// 关闭连接 
        /// </summary> 
        public void Close()
        {

            if (inputstream != null) inputstream.Close();

        }
        /// <summary>
        /// 处理 log 
        /// </summary>
        /// <param name="_initinfo"></param>
        /// <param name="_currentInfo"></param>
        public void GetSession(string _initinfo, string _currentInfo)
        {
            string[] returnSpilt;
            try
            {
                if (_initinfo.Trim() != "")
                {
                    this.SessionLog = _currentInfo.Replace(_initinfo, "");
                }
                else
                {
                    this.SessionLog = _currentInfo;
                }
                if (this.SessionLog.IndexOf("\r\n") > 0) //]
                {
                    string NewSession = string.Empty;

                    returnSpilt = this.SessionLog.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                    //this.SessionLog = returnSpilt[returnSpilt.Length - 2];
                    /*取个 倒数第二行的数据 */
                    for (int i = 1; i <= returnSpilt.Length - 2; i++)
                    {
                        NewSession += returnSpilt[i]; //root@ubuntu:/home/yhq/yhq#  这种开头 要删除的
                        if (i != returnSpilt.Length - 2)
                            NewSession += "\r\n";

                        this.SessionLog = NewSession.Trim();
                    }
                    /*去 掉头和尾部的*/
                }
                else
                    this.SessionLog = "";
            }
            catch
            {
                this.SessionLog = _currentInfo;
                return;
            }

        }

        /// <summary>
        /// sfp -m 0 ：查看SFP的实时状态：温度，电压，发射功率，接收功率
        /// </summary>
        /// <param name="_Session"></param>
        /// <returns></returns>
        public Tamir.SharpSsh.SFP_RealTimeInfo GetRealTimeModel(string _Session, int ResuleStartLine)
        {
            Tamir.SharpSsh.SFP_RealTimeInfo model = new Tamir.SharpSsh.SFP_RealTimeInfo();
            ///5
            ///3
            try
            {
                string[] Cmd_Result = _Session.Split(new string[] { "\r\n" }, StringSplitOptions.None);

                int i = ResuleStartLine; //命令开始行
                model.Temperature_ALL = Cmd_Result[i + 0].Substring(Cmd_Result[i + 0].IndexOf(":") + 1, Cmd_Result[i + 0].Length - Cmd_Result[i + 0].IndexOf(":") - 1);
                model.Voltage_ALL = Cmd_Result[i + 1].Substring(Cmd_Result[i + 1].IndexOf(":") + 1, Cmd_Result[i + 1].Length - Cmd_Result[i + 1].IndexOf(":") - 1);
                model.Bias_ALL = Cmd_Result[i + 2].Substring(Cmd_Result[i + 2].IndexOf(":") + 1, Cmd_Result[i + 2].Length - Cmd_Result[i + 2].IndexOf(":") - 1);
                model.TX_Laser_Power_ALL = Cmd_Result[i + 3].Substring(Cmd_Result[i + 3].IndexOf(":") + 1, Cmd_Result[i + 3].Length - Cmd_Result[i + 3].IndexOf(":") - 1);
                model.RX_Laser_Power_ALL = Cmd_Result[i + 4].Substring(Cmd_Result[i + 4].IndexOf(":") + 1, Cmd_Result[i + 4].Length - Cmd_Result[i + 4].IndexOf(":") - 1);

                model.Temperature = model.Temperature_ALL.Substring(0, model.Temperature_ALL.IndexOf("(raw")).Trim(); //
                model.Voltage = model.Voltage_ALL.Substring(0, model.Voltage_ALL.IndexOf("(raw")).Trim();
                model.Bias = model.Bias_ALL.Substring(0, model.Bias_ALL.IndexOf("(raw")).Trim();
                model.TX_Laser_Power = model.TX_Laser_Power_ALL.Substring(0, model.TX_Laser_Power_ALL.IndexOf("(raw")).Replace("mW", "").Trim();
                model.RX_Laser_Power = model.RX_Laser_Power_ALL.Substring(0, model.RX_Laser_Power_ALL.IndexOf("(raw")).Replace("mW", "").Trim();

                return model;
            }
            catch
            {
                return null;
            }
        }
        /// <summary>
        /// 获取 SFP的基本配置sfp -i 0 ：Nominal Bit Rate(光口速率6100)，Link length supported(传输距离15km)，Vendor Name(供应商)，Vendor part number(供应商模型)， Wave length(波长1310nm),Vendor serial number(供应商序列号)
        /// 
        /// </summary>
        /// <param name="_Session"></param>
        /// <returns></returns>
        public Tamir.SharpSsh.SFP_BaseInfo GetBaseInfoModel(string _Session, int ResuleStartLine)
        {
            Tamir.SharpSsh.SFP_BaseInfo base_model = new Tamir.SharpSsh.SFP_BaseInfo();

            try
            {

                string[] Cmd_Result3 = _Session.Split(new string[] { "\r\n" }, StringSplitOptions.None);

                int j = ResuleStartLine;//命令开始行
                base_model.Nominal_Bit_Rate = Cmd_Result3[8 + j].Substring(Cmd_Result3[8 + j].IndexOf(":") + 1, Cmd_Result3[8 + j].Length - Cmd_Result3[8 + j].IndexOf(":") - 1).Trim();   // 11
                base_model.Link_length_supported = Cmd_Result3[11 + j].Substring(Cmd_Result3[11 + j].IndexOf(":") + 1, Cmd_Result3[11 + j].Length - Cmd_Result3[11 + j].IndexOf(":") - 1).Trim(); //15
                base_model.Vendor_Name = Cmd_Result3[17 + j].Substring(Cmd_Result3[17 + j].IndexOf(":") + 1, Cmd_Result3[17 + j].Length - Cmd_Result3[17 + j].IndexOf(":") - 1).Trim(); //28 
                base_model.Vendor_part_number = Cmd_Result3[19 + j].Substring(Cmd_Result3[19 + j].IndexOf(":") + 1, Cmd_Result3[19 + j].Length - Cmd_Result3[19 + j].IndexOf(":") - 1).Trim();//32
                base_model.Wave_length = Cmd_Result3[21 + j].Substring(Cmd_Result3[21 + j].IndexOf(":") + 1, Cmd_Result3[21 + j].Length - Cmd_Result3[21 + j].IndexOf(":") - 1).Trim();  //36
                base_model.Vendor_serial_number = Cmd_Result3[25 + j].Substring(Cmd_Result3[25 + j].IndexOf(":") + 1, Cmd_Result3[25 + j].Length - Cmd_Result3[25 + j].IndexOf(":") - 1).Trim();  //36


                return base_model;
            }
            catch
            {
                return null;
            }
        }
        /*FSIH类 命令结果的处理 */
        public string GetCmdResulte(int ResulteStartLine, int ResulteEndLine, string _Session)
        {
            try
            {
                string cmdResulte = "";
                string[] Cmd_Result3 = _Session.Split(new string[] { "\r\n" }, StringSplitOptions.None);
                for (int i = ResulteStartLine; i <= ResulteEndLine; i++)
                {
                    if (i != ResulteEndLine)
                        cmdResulte += Cmd_Result3[i] + "\r\n";
                }
                return cmdResulte;
            }
            catch
            {
                return "";
            }

        }

    }
}
